package com.lanou.moving.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.lanou.moving.R;
import com.lanou.moving.activity.PlayMusicActivity;
import com.lanou.moving.adapter.SongListViewAdapter;
import com.lanou.moving.base.BaseFragment;
import com.lanou.moving.entity.MusicInfo;
import com.lanou.moving.entity.SearchSongRoot;
import com.lanou.moving.entity.dao.RecentlyPlay;
import com.lanou.moving.entity.dao.RecentlyPlayDao;
import com.lanou.moving.eventBus.MyEventBus;
import com.lanou.moving.singleton.DaoSingleton;
import com.lanou.moving.utils.MyConfig;
import com.lanou.moving.volley.VolleySingleton;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import de.greenrobot.event.EventBus;

/**
 * Created by dllo on 15/10/23.
 */
public class SongFragment extends BaseFragment implements AdapterView.OnItemClickListener {
    private String url;
    private ListView song_listview;
    private VolleySingleton volleySingleton;
    private List<SearchSongRoot.DataEntity> data;
    private SongListViewAdapter adapter;
    private View view;
    private List<MusicInfo> musicInfoList;
    //数据库表
    private RecentlyPlayDao recentlyPlayDao;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.search_song_listview, null);
        volleySingleton = VolleySingleton.getInstance(mContext);
        recentlyPlayDao = DaoSingleton.getInstance().getRecentlyPlayDao();
        song_listview = (ListView) view.findViewById(R.id.song_listview);
        song_listview.setSelector(R.color.mine_framelayout);
        song_listview.setOnItemClickListener(this);
        return view;

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    private void initData() {
        //接收数据替换q
        String q = MyConfig.getSharePreStr(getActivity(), "Searchcontent", "url");
        url = "http://api.dongting.com/misc/search/song?uid=99000628313628&hid=8416241845401534&" +
                "from=android&resolution=720x1280&net=2&api_version=1.0&utdid=VZqOM5MSBmADAKxkiVwUrSPw&page=" +
                "1&longitude=0.0&user_id=0&splus=4.4.4%252F19&tid=0&client_id=eb737a691df485d6a18833a17cf3c822&f=f168&os=4.4.4&app=ttpod&rom=Xiaomi%252Fgucci%252Fgucci%253A4.4.4%252FKTU84P%252F5.10.15%253Auser%252Frelease-keys" +
                "&alf=alf700159&imei=99000628313628&cpu=msm8916&agent=none&size=50&v=v8.2.0.2015091720" +
                "&s=s200&ram=920276+kB&" +
                "q=" +
                q +
                "&active=0&latitude=0.0&language=zh&imsi=460036001992680&mid=HM%2BNOTE%2B1S&cpu_model=Qualcomm+Technologies%2C+Inc+MSM8916";
        JsonObjectRequest jr = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                String string = response.toString();
                SearchSongRoot songRoot = JSON.parseObject(string, SearchSongRoot.class);
                data = songRoot.getData();
                adapter = new SongListViewAdapter(getActivity(), data);
                song_listview.setAdapter(adapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(jr);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        SearchSongRoot.DataEntity songsEntity = (SearchSongRoot.DataEntity) parent.getItemAtPosition(position);
        if ((songsEntity.getUrlList() != null && songsEntity.getUrlList().size() > 0)) {
            RecentlyPlay recentlyPlay = new RecentlyPlay();
            recentlyPlay.setSongName(songsEntity.getName());
            recentlyPlay.setPlayUrl(songsEntity.getUrlList().get(0).getUrl());
            recentlyPlay.setDuration((long) songsEntity.getUrlList().get(0).getDuration());
            recentlyPlay.setSingerName(songsEntity.getSingerName());
            recentlyPlay.setSongId((long) songsEntity.getSongId());
            recentlyPlay.setResource("网络");
            recentlyPlayDao.insertOrReplace(recentlyPlay);

            EventBus.getDefault().post(new MyEventBus.PlayMusic(1));
            musicInfoList = new ArrayList<>();

            for (SearchSongRoot.DataEntity entity : data) {
                if (entity.getUrlList() != null && entity.getUrlList().size() > 0) {
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setSongName(entity.getName());
                    musicInfo.setAlbum(entity.getAlbumName());
                    musicInfo.setAlbumId(entity.getAlbumId());
                    musicInfo.setUrl(entity.getUrlList().get(0).getUrl());
                    musicInfo.setDuration(entity.getUrlList().get(0).getDuration());
                    musicInfo.setSingerName(entity.getSingerName());
                    musicInfo.setResouce("网络");
                    musicInfoList.add(musicInfo);
                }
            }

            Intent intent = new Intent(mContext, PlayMusicActivity.class);
            EventBus.getDefault().post(new MyEventBus.Deliver(musicInfoList, songsEntity.getName()));
            intent.putExtra("songName", songsEntity.getName());
            intent.putExtra("duration", songsEntity.getUrlList().get(0).getDuration());
            intent.putExtra("resource", "网络");
            intent.putExtra("albumId", songsEntity.getAlbumId());
            intent.putExtra("singerName", songsEntity.getSingerName());
            startActivity(intent);
        } else {
            Toast.makeText(mContext, "暂时无法播放此歌曲", Toast.LENGTH_LONG).show();
        }
    }
}
